"""Plot distribution function of time delays of cascade steps."""
import pylab as plt
import sys
import os
import numpy as np
from utilities import *
from params import *

delays = []
tweet_file = os.path.join(WORKDIR, 'geocascades',  'tweets_delays_2days.txt')
for line in open(tweet_file):
    delay,size,depth = map(int,line.split(' '))
    delays.append(max(1.0,delay))


durations = []
cascade_file = os.path.join(WORKDIR, 'geocascades', 'cascade_duration_2days.txt')
for line in open(cascade_file):
    duration,size, depth= map(int,line.split(' '))
    if size > 2:
        durations.append(max(1.0,duration))

x,y = log_ecdf(delays,normed=True)
x2,y2 = log_ecdf(durations,normed=True)
plt.figure()
plt.clf()
plt.axes(FIG_AXES2)
plt.semilogx(x,y,'k-')
plt.semilogx(x2,y2,'k--')
plt.xlabel('Delay [s]')
plt.ylabel('CDF')
plt.legend(['Step','Cascade'],
        numpoints=1,loc='lower right')
plt.grid(True)
plt.savefig('dist_delay.pdf')
plt.close()

durations.sort()
print 'Average duration ', 1.0*sum(durations)/len(durations)
print 'Median duration ', durations[len(durations)//2]
print 'Max duration ', durations[-1]

delays.sort()
print 'Average delays ', 1.0*sum(delays)/len(delays)
print 'Median delays ', delays[len(delays)//2]
print 'Max delays ', delays[-1]
sys.exit()



x,y,labels = [],[],[]
MAX_DEPTH = 6
for depth in range(1,MAX_DEPTH):
    print 'Depth = %d'%depth
    delays = [a for a,b in data if b == depth]
    print "Delays ", len(delays)

    delays = filter(lambda x: x>0, delays)
    if not delays:
        continue
    print "Non-zero delays ", len(delays)
    print 'Maximum delay ', max(delays)

    a,b = ecdf(delays,normed=True, inverse=False)
    x.append(a)
    y.append(b)
    labels.append('Depth %d'%depth)

print 'Depth larger or equal than ', MAX_DEPTH
delays = [a for a,b in data if b >= MAX_DEPTH]
print "Delays ", len(delays)
print 'Maximum delay ', max(delays)
delays = filter(lambda x: x>0, delays)
print "Non-zero delays ", len(delays)

a,b = ecdf(delays,normed=True, inverse=False)
x.append(a)
y.append(b)
labels.append('Depth %d or above'%MAX_DEPTH)

for xv,yv in zip(x,y):
    plt.semilogx(xv,yv,'.-')

plt.grid(True)
plt.legend(labels,loc='upper left')
plt.savefig('dist_delay_depth.png')
plt.close()

delays = [a for a,b in data]

delays = filter(lambda x: x>0, delays)
x,y = ecdf(delays,normed=True, inverse=False)

plt.semilogx(x,y,'.-')
plt.xlabel('Seconds')
plt.grid(True)
plt.savefig('dist_delay.png')
plt.close()
